package com.xxx.auth;

import com.xxx.auth.common.util.PasswordEncoder;
import com.xxx.auth.common.util.PermissionUtil;
import com.xxx.auth.entity.Permission;
import com.xxx.auth.entity.User;
import com.xxx.auth.repository.PermissionCategoryRepository;
import com.xxx.auth.repository.PermissionRepository;
import com.xxx.auth.repository.UserRepository;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

@EntityScan("com.xxx.auth")
@EnableJpaAuditing
@EnableJpaRepositories(basePackages = "com.xxx.auth")
@SpringBootApplication(scanBasePackages = "com.xxx.auth")
@RequiredArgsConstructor
@Slf4j
public class AuthenticationApplication implements ApplicationListener<ApplicationStartedEvent> {

    public static void main(String[] args) {
        try {
            Class.forName("org.postgresql.Driver");
            Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/authentication", "postgres", "postgres");
            connection.createStatement().execute("create schema if not exists public");
            connection.close();
        } catch (Exception e) {
            log.error("初始化失败", e);
        }

        SpringApplication.run(AuthenticationApplication.class, args);
    }

    private final UserRepository userRepository;
    private final PermissionRepository permissionRepository;
    private final PermissionCategoryRepository permissionCategoryRepository;

    @Override
    public void onApplicationEvent(@NonNull ApplicationStartedEvent event) {
        createUser();
        createPermission();
    }

    private void createUser() {
        User user = new User();
        user.setUsername("test");
        user.setName("test");
        user.setPassword(new PasswordEncoder().encode("1234"));

        userRepository.save(user);
    }

    private void createPermission() {
        List<Permission> permissionList = PermissionUtil.getPermissionList("permission/permission.txt", permissionCategoryRepository);
        permissionRepository.saveAll(permissionList);
    }

}
